package com.fly.graphql_demo.business.user.provider

import com.coxautodev.graphql.tools.GraphQLMutationResolver
import com.coxautodev.graphql.tools.GraphQLQueryResolver
import com.coxautodev.graphql.tools.SchemaParser
import com.fly.graphql_demo.business.user.data.User
import com.fly.graphql_demo.business.user.data.UserList
import com.fly.graphql_demo.business.user.data.UserParam
import com.fly.graphql_demo.business.user.service.UserService
import graphql.GraphQL
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
import javax.annotation.PostConstruct

@Component
class UserProvider {

    private lateinit var graphQL: GraphQL

    @Autowired
    private lateinit var userService: UserService

    @Bean
    fun graphQL(): GraphQL = graphQL

    @PostConstruct
    fun init() {
        SchemaParser.newParser()
            .file("graphql/base.graphqls")
            .resolvers(Query(), Mutation())
            .file("graphql/user.graphqls")
            .resolvers(UserResolver(userService))
            .build()
            .makeExecutableSchema()
            .run {
                graphQL = GraphQL.newGraphQL(this).build()
            }

    }

}


class Query : GraphQLQueryResolver, GraphQLMutationResolver {

}


class Mutation: GraphQLQueryResolver, GraphQLMutationResolver {
}


@Component
class UserResolver(private val userService: UserService) : GraphQLQueryResolver, GraphQLMutationResolver {

    /**
     *    {
    "query": "mutation saveUser($userParam: UserParam){saveUser(userParam: $userParam){email, name}}",
    "variables": {"userParam": {
    "email": "943169931",
    "name": "fuck"
       }
      }
     }
     */
    fun saveUser(userParam: UserParam): User = userService.saveUser(userParam)
    fun updateUser(userParam: UserParam): User? = userService.updateUser(userParam)
    fun deleteUser(id: Int): Boolean = userService.deleteUser(id)

    /**
     * {
     *  "query": "query queryId($id: ID){queryId(id: $id){name, email,id}}",
     *  "variables": {"id": 1}
     * }
     */
    fun queryId(id: Int): User = userService.queryId(id)

    /**
     * {
     *   "query": "query queryUserList{queryUserList{users{name,email}, total}}
     * }
     */
    fun queryUserList(): UserList = userService.queryUserList()
    fun version() = "1.0"
}